import { Table, Button, Popconfirm, Tooltip, Modal, Divider } from 'antd';
import styles from './index.less';
import { useMount, useSetState, useUnmount } from 'ahooks';
import classnames from 'classnames';
import { connect } from 'dva';
// components
import { TRMessage, TRDefault } from '@/components';
import { default as AppMessageModal } from './components/AppMessageModal';
import { EditOutlined } from '@/utils/antdIcons';
import { getApplicationList, delApplication } from '@/services/power';
import { APP_TYPE, ADD_APP, UPKDATE_APP, DEL_APP } from './helper.js';
import { tableLocale } from '#/components/PageEmpty';

const AppManagement = (props) => {
  const pagination = {
    current: 1,
    size: 1000,
  };

  const [state, setState] = useSetState({
    dataList: [],
    pageLoading: false,
    addAppAuthority: false,
    updateAppAuthority: false,
    delAppAuthority: false,
    clientHeight: document?.body?.clientHeight - 150,
  });

  useMount(() => {
    _getApplicationList();
    window.addEventListener('resize', onChangeTableHeight);
  });

  useUnmount(() => {
    window.removeEventListener('resize', onChangeTableHeight);
  });

  const onChangeTableHeight = () => {
    const calcHeight = document?.body?.clientHeight - 150;
    let clientHeight = calcHeight < 150 ? 150 : calcHeight;
    setTimeout(() => {
      setState({ clientHeight });
    }, 500);
  };

  useMount(() => {
    const addApp = props.buttonPermissions.find((item) => item.menuCode === ADD_APP);
    const updateApp = props.buttonPermissions.find((item) => item.menuCode === UPKDATE_APP);
    const delApp = props.buttonPermissions.find((item) => item.menuCode === DEL_APP);
    setState({
      addAppAuthority: !!addApp,
      updateAppAuthority: !!updateApp,
      delAppAuthority: !!delApp,
    });
  });

  const _getApplicationList = async () => {
    setState({ pageLoading: true });
    const res = await getApplicationList(pagination);
    setState({ pageLoading: false });
    const dataList = res?.data?.list || [];
    setState({ dataList });
  };

  const columns = [
    {
      title: '应用名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '应用说明',
      dataIndex: 'applicationExplain',
      key: 'applicationExplain',
      render: (text) => {
        return (
          <Tooltip
            trigger={['click']}
            title={() => <div style={{ whiteSpace: 'pre-line' }}>{text || ''}</div>}
          >
            <span className={styles.whiteSpace}>{text}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <div className={styles.operationColumn}>
          <a className={styles.editStyle} onClick={() => _handleEdit(record)}>
            编辑
          </a>

          <Divider type="vertical" />

          {state.delAppAuthority && !record.defaultFlag ? (
            <Popconfirm
              title="确认删除？"
              onConfirm={() => _confirmDelte(record.customApplicationId)}
              onCancel={() => {}}
              okText="是"
              cancelText="否"
            >
              <a className={classnames(styles.editStyle)}>删除</a>
            </Popconfirm>
          ) : (
            <a className={styles.disabled}>删除</a>
          )}
        </div>
      ),
    },
  ];
  const _handleEdit = (row) => {
    const { customApplicationId, defaultFlag } = row;
    handleApp(2, customApplicationId, defaultFlag); // 2 编辑
  };

  // 删除应用
  const _confirmDelte = async (id) => {
    setState({
      pageLoading: true,
    });
    const res = await delApplication(id);
    setState({
      pageLoading: false,
    });
    _getApplicationList();
    props.dispatch({
      type: 'user/onRefreshMenu',
      payload: { firstJump: true },
    });
  };

  const handleApp = async (type, detailId = '', defaultFlag = false) => {
    const { addAppAuthority, updateAppAuthority } = state;
    if (!addAppAuthority && type === 1) return TRMessage.info('请联系管理员获取相关权限');
    const modal = await AppMessageModal.show({
      modelType: APP_TYPE[type],
      detailId: detailId,
      defaultFlag,
      updateAppAuthority,
    });
    if (modal?.success) {
      _getApplicationList();
      props.dispatch({
        type: 'user/onRefreshMenu',
        payload: { firstJump: true },
      });
    }
  };

  const _renderList = () => {
    if (!state.pageLoading && !state.dataList.length) return <TRDefault type="emptysm" />;
    return (
      <Table
        locale={tableLocale}
        loading={state.pageLoading}
        rowClassName={styles.rowStyle}
        size="small"
        rowKey="customApplicationId"
        columns={columns}
        dataSource={state.dataList}
        pagination={false}
        scroll={{ y: state?.clientHeight || 150 }}
      />
    );
  };

  return (
    <div className={styles.main}>
      <div className={styles.header}>
        <p className={styles.title}>应用管理</p>
        <Button
          style={{
            height: '32px',
            fontSize: '14px',
            borderRadius: '5px',
            borderColor: state.addAppAuthority ? 'var(--bd-primary)' : '#606366',
            background: state.addAppAuthority ? 'var(--base2)' : '#606366',
            color: state.addAppAuthority ? 'var(--font-active)' : '#908f88',
          }}
          type="primary"
          icon={<EditOutlined />}
          onClick={() => handleApp(APP_TYPE['add'])}
        >
          新建应用
        </Button>
      </div>
      <div className={styles.tableEdit}>{_renderList()}</div>
    </div>
  );
};

export default connect(({ user }) => ({
  appName: user.appName,
  menuList: user.menuList,
  buttonPermissions: user.buttonPermissions,
}))(AppManagement);
